import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/Login/Login.vue')
  },
	{
	  path: '/search',
	  name: 'search',
	  component: () => import('../views/Search')
	},
	{
		// params在切换返回的时候会丢失参数,需要这样写解决问题
	  path: '/detail/:pid',
	  name: 'Detail',
	  component: () => import('../views/Detail')
	},
	{
	  path: '/pay',
	  name: 'Pay',
	  component: () => import('../views/Pay')
	},
	{
	  path: '/address',
	  name: 'Address',
	  component: () => import('../views/Address')
	},
	{
		path: '/main',
		name: 'Main',
		component: () => import('../views/Main.vue'),
		children: [
			{
				path: '/main',
				name: 'default',
				redirect: 'home'
			}, 
			{
				path: "home",
				name: "Home",
				component: () => import("../views/Tabbar/Home")
			},
			{
				path: "menu",
				name: "Menu",
				component: () => import("../views/Tabbar/Menu")
			},
			{
				path: "shopbag",
				name: "Shopbag",
				component: () => import("../views/Tabbar/Shopbag")
			},
			{
				path: "my",
				name: "My",
				component: () => import("../views/Tabbar/My")
			}
		]
	},
	{
	  path: '/userset',
	  name: 'Userset',
	  component: () => import('../views/User/userset')
	},
	{
	  path: '/collect',
	  name: 'Collect',
	  component: () => import('../views/User/collect')
	},
	{
	  path: '/order',
	  name: 'Order',
	  component: () => import('../views/User/order')
	},
	{
	  path: '/addressset',
	  name: 'AddressSet',
	  component: () => import('../views/User/addressset')
	},
	{
	  path: '/safety',
	  name: 'Safety',
	  component: () => import('../views/User/safety')
	}
]

const router = new VueRouter({
	routes
})

// // 挂载路由导航守卫
router.beforeEach((to, from, next) => {
	// to => 将要访问的路径
	// from => 从哪个路径跳转而来
	// next => 是个函数，表示放行
	// next()=>放行   next('/login')=>	强制跳转

	if (to.path === '/') {
		return next()
	} else if (to.path === '/main/home') {
		return next()
	}

	// 获取 token
	const tokenStr = window.sessionStorage.getItem('token')

	if (!tokenStr) {
		return next('/')
	} else {
		next()
	}
})

export default router
